//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<CSimpleMesh.cpp>
///	@path	~/src/graphics/common/
///	@date	2009/01/01
///	@desc	.

#include "config/config.h"

#include "graphics/common/CSimpleMesh.h"

namespace xeres {

	IMPL_IOBJECT_CLASS( CSimpleMesh );
	
	// CSimpleMesh
	CSimpleMesh::CSimpleMesh( TopologyType type , RefWeak<IVertexLayout> layout , RefWeak<IVertexBuffer> vertex , RefWeak<IVertexIndex> index )
		: m_type( type )
		, m_layout( layout )
		, m_vertex( vertex )
		, m_index( index )
	{
		size_t count = 0;
		if( m_index.IsValid() )
			count = m_index->GetCount();
		m_prim = d3d_prim_count( type , vertex->GetCount() , count );
	}
	// ~CSimpleMesh
	CSimpleMesh::~CSimpleMesh( void )
	{
	}
	// OnLostDevice
	bool CSimpleMesh::OnLostDevice( void )
	{
		return true;
	}
	// OnResetDevice
	bool CSimpleMesh::OnResetDevice( RefWeak<IDevice> device )
	{
		return true;
	}
	// GetLayout
	RefWeak<IVertexLayout> CSimpleMesh::GetLayout( void )
	{
		return m_layout;
	}
	// EstablishBuffer
	void CSimpleMesh::EstablishBuffer( RenderContext& rc )
	{
		m_layout->ApplyLayout( rc );
		m_vertex->ApplyStream( rc , 0 );
		if( m_index.IsValid() )
			m_index->ApplyIndex( rc );

		if( rc.GetDX10() )
		{
			D3D10_PRIMITIVE_TOPOLOGY type = d3d_topology_type10(m_type);
			rc.GetDX10()->IASetPrimitiveTopology( type );
		}
	}
	// Draw
	void CSimpleMesh::Draw( RenderContext& rc )
	{
		if( rc.GetDX9() )
		{
			D3DPRIMITIVETYPE type = d3d_topology_type9(m_type);
			if( m_index.IsValid() )
			{
				rc.GetDX9()->DrawIndexedPrimitive( type , 0 , 0 , m_vertex->GetCount() , 0 , m_prim );
			}
			else
			{
				rc.GetDX9()->DrawPrimitive( type , 0 , m_prim );
			}
		}
		else
		{
			if( m_index.IsValid() )
			{
				rc.GetDX10()->DrawIndexed( m_index->GetCount() , 0 , 0 );
			}
			else
			{
				rc.GetDX10()->Draw( m_vertex->GetCount() , 0 );
			}
		}
	}
	// ClearBuffer
	void CSimpleMesh::ClearBuffer( RenderContext& rc )
	{
		if( rc.GetDX9() )
		{
			rc.GetDX9()->SetStreamSource( 0 , NULL , 0 , 0 );
			if( m_index.IsValid() )
				rc.GetDX9()->SetIndices( NULL );
		}
	}
	// GetSlotCount
	size_t CSimpleMesh::GetSlotCount( void )
	{
		return 0;
	}
	// GetVertex
	RefWeak<IVertexBuffer> CSimpleMesh::GetVertex( size_t slot )
	{
		XS_ASSERT( slot == 0 );
		return m_vertex;
	}
	// GetIndex
	RefWeak<IVertexIndex> CSimpleMesh::GetIndex( void )
	{
		return m_index;
	}
	
} // namespace xeres
